#include "math.h"
#include "gamma.h"


float gamma_table[256];
float cur_gamma = 0.0;


void CreateGammaTable(float gamma, float *table)
{
	for (int x = 0; x < 256; x++)
		table[x] = (float) pow((float) x / 255.0f, gamma);
}


void InitGamma(float gamma)
{
	if (cur_gamma == gamma)
		return;

	CreateGammaTable(gamma, gamma_table);

	cur_gamma = gamma;
}

void compute_linear_to_gamma(unsigned char table[4096 * 3])
{
	for (int x = 0; x < 4096 * 3; x++)
	{
		float temp = (float)(pow(x / 4096.0, 1.0 / 1.75) * 255.0);
		table[x] = (temp > 255.0f ? 255 : (unsigned char)temp);
	}
}


void compute_linear_to_gamma_with_shoulder(unsigned char table[4096 * 3], float cut)
{
	float scale = 2*(1-cut)/3.14159265358979323f;
	float invscale = 1.0f / scale;
	float val;

	for (int x = 0; x < 4096 * 3; x++)
	{
		val = x / 4096.0f;
		if (val > cut) 
		{
			val = scale * (float) atan((val-cut) * invscale) + cut;
		}
		val = (float)(pow(val, 1.0f / 1.75f) * 255.0f);
		table[x] = (val > 255.0f ? 255 : (unsigned char)val);
	}


}
